package com.imarkket.Dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Spinner;

import com.imarkket.Library.c_logging;
import com.imarkket.R;
import com.imarkket.sqlite.handler.c_bd_handler;

import java.util.List;

public class c_dialog_NewProducto extends DialogFragment {

    int PickerValue = 1;
    String SpinnerValue = "";

    public interface ListenerInterface {
        void onSubmitListenerInterface_NewProducto(String NewProduct, int ProductCount );
    }
    public ListenerInterface mListener;

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the
            // host
            mListener = (ListenerInterface) activity;

        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement DialogListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_sl_pd_New_Product));

        // Use the Builder class for convenient dialog construction
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Vista del Dialog
        View view = getActivity().getLayoutInflater().inflate(R.layout.l_df_anadir_producto, null);

        builder.setView(view);

        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.l_df_anadir_producto, null))
                // Add action buttons

                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // No hacemos nada, override del método onStart y ahí hago todo.
                        // He tenido que hacer esto porque si lo implementaba aquí
                        // Se cerraba el cuadro de dialogo y siempre y no se podía evitar.
                        // si lo hago en onstart ya se cierra cuando quiera
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_No));
                    }
                });

        // Create the AlertDialog object and return it
        return builder.create();
    }

    @Override
    public void onStart() {
        super.onStart();    //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
        AlertDialog d = (AlertDialog) getDialog();

        if (d != null) {
            // Number Picker que indica la cantidad de productos
            NumberPicker np = (NumberPicker)getDialog().findViewById(R.id.Product_Picker);
            np.setMinValue(1);// restricted number to minimum value i.e 1
            np.setMaxValue(99);// restricked number to maximum value i.e. 31
            np.setWrapSelectorWheel(true);

            np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener()
            {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal)
                {
                    // TODO Auto-generated method stub
                    PickerValue = newVal;
                    c_logging.getInstance().log(c_logging.LOG_INFO, "Old:" + oldVal + " New:" + newVal );
                }
            });

            // Combo con los productos
            Spinner spinner = (Spinner) getDialog().findViewById(R.id.product_spinner);
            // Create an ArrayAdapter using the string array and a default spinner layout
            /*
            spinner.setOnItemSelectedListener(new OnItemSelectedListener()

            {
                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
                {
                    Toast.makeText(topThis, "derp", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parentView)
                {
                    Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
                }
            });
            spinner.setonItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
                // An item was selected. You can retrieve the selected item using
                // parent.getItemAtPosition(pos)
            }
            */

            // Base de Datos
            c_bd_handler BD;
            BD = new c_bd_handler(getActivity());
            BD.fnc_bd_handler_init(getActivity());
            // Spinner Drop down elements
            List<String> productos = BD.fnc_getAll_Productos();
            // Creating adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, productos);

            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            spinner.setAdapter(dataAdapter);
            BD.close();

            Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Yes));

                    EditText m = (EditText) getDialog().findViewById(R.id.new_producto);
                    m.setError(null);

                    if (TextUtils.isEmpty(m.getText().toString())) {
                        m.setError(getString(R.string.st_la_Field_Required));
                        m.requestFocus();
                    } else {
                        //c_logging.getInstance().log(c_logging.LOG_INFO, "Nuevo Producto: ("+m.getText().toString()+")" + spinner.getSelectedItem().toString());
                        mListener.onSubmitListenerInterface_NewProducto(m.getText().toString(), PickerValue);
                        dismiss();
                    }
                }
            });
        }
    }
}
